<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="fusion-docs">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="fusion-docs">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>Http Route（异步处理器） · Akka Fusion</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#3f51b5" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="indigo"
data-md-color-accent="red"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Akka Fusion" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Akka Fusion
</span>
<span class="md-header-nav__topic">
Http Route（异步处理器）
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/akka-fusion/akka-fusion"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
akka-fusion/akka-fusion
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Akka Fusion" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Akka Fusion">
Akka Fusion
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/akka-fusion/akka-fusion"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
akka-fusion/akka-fusion
</div>
</a>

</div>
<ul>
  <li><a href="../intro/index.html" class="page">简介</a></li>
  <li><a href="../core/index.html" class="page">核心</a>
  <ul>
    <li><a href="../core/akka-extension.html" class="page">Akka Extension（扩展）</a></li>
    <li><a href="../core/http-route.html" class="active page">Http Route（异步处理器）</a></li>
    <li><a href="../core/fusion-core.html" class="page">FusionCore</a></li>
  </ul></li>
  <li><a href="../http/index.html" class="page">HTTP</a>
  <ul>
    <li><a href="../http/getting.html" class="page">开始</a></li>
    <li><a href="../http/management.html" class="page">管理API</a></li>
    <li><a href="../http/interceptor-chain.html" class="page">Interceptor Chain（拦截器链）</a></li>
  </ul></li>
  <li><a href="../discovery-client/index.html" class="page">服务注册、发现（Client）</a>
  <ul>
    <li><a href="../discovery-client/nacos.html" class="page">连接 Nacos</a></li>
  </ul></li>
  <li><a href="../http-gateway/index.html" class="page">HTTP 代理网关</a></li>
  <li><a href="../jdbc/index.html" class="page">Jdbc</a></li>
  <li><a href="../slick/index.html" class="page">Slick</a></li>
  <li><a href="../mybatis/index.html" class="page">MyBatis</a>
  <ul>
    <li><a href="../mybatis/getting.html" class="page">起步</a></li>
    <li><a href="../mybatis/configuration.html" class="page">配置</a></li>
  </ul></li>
  <li><a href="../data-mongodb/index.html" class="page">Data Mongodb</a></li>
  <li><a href="../data-kafka/index.html" class="page">Data Kafka</a>
  <ul>
    <li><a href="../data-kafka/getting.html" class="page">开始</a></li>
    <li><a href="../data-kafka/producer.html" class="page">Kafka Producer</a></li>
    <li><a href="../data-kafka/consumer.html" class="page">Kafka Consumer</a></li>
  </ul></li>
  <li><a href="../inject/index.html" class="page">依赖管理</a>
  <ul>
    <li><a href="../inject/guice.html" class="page">使用 Guice 进行类依赖管理</a></li>
  </ul></li>
  <li><a href="../log/index.html" class="page">日志</a></li>
  <li><a href="../configuration/index.html" class="page">配置</a>
  <ul>
    <li><a href="../configuration/core.html" class="page">Fusion Core 配置</a></li>
    <li><a href="../configuration/http.html" class="page">Fusion HTTP 配置</a></li>
    <li><a href="../configuration/http-gateway.html" class="page">Fusion HTTP Gateway 配置</a></li>
    <li><a href="../configuration/jdbc.html" class="page">Fusion JDBC 配置</a></li>
    <li><a href="../configuration/slick.html" class="page">Fusion Slick 配置</a></li>
    <li><a href="../configuration/mybatis.html" class="page">Fusion Mybatis 配置</a></li>
    <li><a href="../configuration/mongodb.html" class="page">Fusion Mongodb 配置</a></li>
    <li><a href="../configuration/kafka.html" class="page">Fusion Kafka 配置</a></li>
  </ul></li>
  <li><a href="../reactivemanifesto.html" class="page">反应式宣言 2.0</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../core/http-route.html#http-route-异步处理器-" class="header">Http Route（异步处理器）</a>
  <ul>
    <li><a href="../core/http-route.html#requestcontext" class="header">RequestContext</a></li>
    <li><a href="../core/http-route.html#routeresult" class="header">RouteResult</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 2.0.6
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../core/http-route.html#http-route-异步处理器-" class="header">Http Route（异步处理器）</a>
  <ul>
    <li><a href="../core/http-route.html#requestcontext" class="header">RequestContext</a></li>
    <li><a href="../core/http-route.html#routeresult" class="header">RouteResult</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#http-route-异步处理器-" name="http-route-异步处理器-" class="anchor"><span class="anchor-link"></span></a>Http Route（异步处理器）</h1>
<pre class="prettyprint"><code class="language-scala">type Route = RequestContext =&gt; Future[RouteResult]
</code></pre>
<p>Fusion基于Akka HTTP实现了HTTP 1.0、1.1和2.0协议的请求响应处理，同时还支持GRPC。<code>Route</code>是<code>RequestContext =&gt; Future[RouteResult]</code>的类型定义，从接收到一个请求开始，返回一个异步的HTTP响应。原始的<code>HttpRequest</code>被包裹在一个<code>RequestContext</code>请求上下文中，而响应结果也使用了<code>RouteResult</code>进行封装。</p>
<h2><a href="#requestcontext" name="requestcontext" class="anchor"><span class="anchor-link"></span></a>RequestContext</h2>
<p><code>RequestContext</code>的一个典型实现如下：</p>
<pre class="prettyprint"><code class="language-scala">trait RequestContext {
  val request: HttpRequest
  val unmatchedPath: Uri.Path
  implicit def executionContext: ExecutionContextExecutor
  implicit def materializer: Materializer
  def log: LoggingAdapter
  def settings: RoutingSettings
  def parserSettings: ParserSettings
  def reconfigure(
    executionContext: ExecutionContextExecutor = executionContext,
    materializer:     Materializer             = materializer,
    log:              LoggingAdapter           = log,
    settings:         RoutingSettings          = settings): RequestContext
  def complete(obj: ToResponseMarshallable): Future[RouteResult]
  def reject(rejections: Rejection*): Future[RouteResult]
  def redirect(uri: Uri, redirectionType: Redirection): Future[RouteResult]
  def fail(error: Throwable): Future[RouteResult]
  // ....
}
</code></pre>
<p><strong><code>request</code></strong></p>
<p>保存了原始的<code>HttpRequest</code>对象。</p>
<p><strong><code>unmatchedPath</code></strong></p>
<p>保存了当前Akka HTTP Routing层级下还未匹配的路径。如下面的路由定义，在<code>account</code>这一级，请求<code>Uri.Path</code>: <code>/api/v4/account/user/page</code>对应的<code>unmatchedPath</code>保持的未匹配路径为：<code>/user/page</code>。 </p>
<p><strong><code>complete</code></strong></p>
<p>请求正常完成时，返回数据通过<code>complete</code>函数来响应。<code>complete</code>函数通过<code>ToResponseMarshallable</code>来决定数据类型该怎么处理（序列化），Akka HTTP默认已提供了大部分数据类型的处理方式，我们可以很方便的对自定义数据实现<code>ToResponseMarshallable</code>。对应JSON类型的数据响应，<a href="https://github.com/hseeberger/akka-http-json">https://github.com/hseeberger/akka-http-json</a> 是一个很好的起点。</p>
<p><strong><code>reject</code></strong></p>
<p><code>reject</code>顾名思义，调用它将拒绝当前请求。它需要传一个或多个实现了<code>Rejection</code>接口的类型。akka-fusion默认的reject处理如下：</p>
<pre class="prettyprint"><a class="icon go-to-source" href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-http-client/src/main/scala/fusion/http/util/BaseRejectionBuilder.scala#L33-L82" target="_blank" title="Go to snippet source"></a><code class="language-scala">def rejectionBuilder: Builder =
  RejectionHandler
    .newBuilder()
    .handle {
      case MissingQueryParamRejection(parameterName) =&gt;
        complete(jsonEntity(BadRequest, s&quot;请求参数 &#39;$parameterName&#39; 缺失&quot;))

      case MissingCookieRejection(cookieName) =&gt;
        val msg = s&quot;无效的Cookie: $cookieName&quot;
        logger.info(msg)
        complete(jsonEntity(BadRequest, msg))

      case ForbiddenRejection(message, cause) =&gt;
        val msg = s&quot;权限禁止：$message&quot;
        logger.warn(msg, cause.orNull)
        complete(jsonEntity(Forbidden, message))

      case SessionRejection(message, cause) =&gt;
        val msg = s&quot;会话认证失败：$message&quot;
        logger.warn(msg, cause.orNull)
        complete(jsonEntity(Unauthorized, msg))

      case AuthorizationFailedRejection =&gt;
        val msg = &quot;会话认证失败&quot;
        logger.warn(msg)
        complete(jsonEntity(Unauthorized, msg))

      case ValidationRejection(err, _) =&gt;
        val msg = &quot;数据校验失败： &quot; + err
        logger.info(msg)
        complete(jsonEntity(BadRequest, msg))
    }
    .handleAll[MethodRejection] { methodRejections =&gt;
      val description = methodRejections.map(_.supported.name).mkString(&quot; or &quot;)
      val msg = s&quot;不支持的方法！当前支持：$description!&quot;
      logger.info(msg)
      complete(jsonEntity(MethodNotAllowed, msg))
    }
    .handleNotFound {
      extractUri { uri =&gt;
        val msg = s&quot;URI: $uri 路径未找到！&quot;
        logger.info(msg)
        complete(jsonEntity(NotFound, msg))
      }
    }
    .handle {
      case rejection =&gt;
        logger.info(rejection.toString)
        complete(jsonEntity(BadRequest, rejection.toString))
    }</code></pre>
<p><strong><code>redirect</code></strong></p>
<p><code>redirect</code>在你需要向请求方返回重定向响应时使用。它有两个参数：</p>
<ol>
  <li><code>uri: Uri</code>：需要生定向的地址</li>
  <li><code>redirectionType: Redirection</code>：HTTP响应状态码，现在可选择的状态码有300到308中的一个</li>
</ol>
<p><strong><code>fail</code></strong></p>
<p>返回异常的快捷函数，大多数情况下不需要使用到这个。</p>
<h2><a href="#routeresult" name="routeresult" class="anchor"><span class="anchor-link"></span></a>RouteResult</h2>
<p><code>akka.http.scaladsl.server.RouteResult</code>接口有两个子类（定义类似）：</p>
<pre class="prettyprint"><code class="language-scala">final case class Complete(response: HttpResponse) extends RouteResult
final case class Rejected(rejections: Seq[Rejection]) extends RouteResult
</code></pre>
<p><code>Complete</code>很直观了，代表请求已完成（HTTP请求已完成，但业务有可能错误）。</p>
<p>而<code>Rejected</code>代表请求被拒绝，一般用于HTTP方法不对、URL路径未找到、请求实体过大等情况。</p>
</div>
<div>
<a href="https://github.com/akka-fusion/akka-fusion/tree/master/fusion-docs/src/main/paradox/core/http-route.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
2.0.6
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../core/akka-extension.html" title="Akka Extension（扩展）" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
Akka Extension（扩展）
</span>
</div>
</a>
<a href="../core/fusion-core.html" title="FusionCore" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
FusionCore
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://akka-fusion.github.io/akka-fusion/" class="md-footer-social__link fa fa-globe"></a><a href="https://github.com/akka-fusion" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
